package io.renren.modules.h5.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.WriterException;
import io.renren.common.sms.YxuntongSms;
import io.renren.common.utils.*;
import io.renren.modules.noc.controller.BaseController;
import io.renren.modules.noc.entity.*;
import io.renren.modules.noc.service.*;
import io.renren.modules.sys.shiro.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 展会
 *
 * @author whc
 * @email hucheng_86@126.com
 * @date 2019-04-03 22:37:46
 */
@Controller
public class NocCommController extends BaseController{
    @Autowired
    private NocMemberService nocMemberService;
    @Autowired
    private NocTemplateService nocTemplateService;
    @Autowired
    private NocBusinessService nocBusinessService;
    @Autowired
    private NocBeerTicketMemberService nocBeerTicketMemberService;
    @Autowired
    private NocBeerTicketBusinessService nocBeerTicketBusinessService;
    @Autowired
    private NocBeerSeatService nocBeerSeatService;
    @Autowired
    private MemberQRCodeUtil memberQRCodeUtil;

    @Value("${ercode.pre}")
    private String _pre;

    //二维码短链接 - 观众(出入证件)
    @RequestMapping(value = "/t/{id}")
    public String t(@PathVariable("id") Integer id,HttpServletRequest request) {
        NocMemberEntity memberEntity = nocMemberService.getById(id);
        if(memberEntity!=null) {
            //获取展会模板，此行不能动
            NocTemplateEntity nocTemplateEntity = nocTemplateService.getById(memberEntity.getTid());
            request.setAttribute("template",nocTemplateEntity);
            request.setAttribute("id", id);
            request.setAttribute("ly", memberEntity.getLy());
            request.setAttribute("tid", memberEntity.getTid());
            request.setAttribute("member", memberEntity);
            //判断观众是否已经兑换啤酒节门票
            Map<String,Object> p = new HashMap<>();
            p.put("tid",memberEntity.getTid());
            p.put("member_id",memberEntity.getId());
            List<NocBeerTicketMemberEntity> list = (List<NocBeerTicketMemberEntity>) nocBeerTicketMemberService.listByMap(p);
            if(list!=null&&list.size()>0){
                request.setAttribute("beer",list.get(0));
            }
            return "modules/h5/ercode";
        }
        return "";
    }

    //二维码短链接 - 展商（出入证）
    @RequestMapping(value = "/s/{id}")
    public String s(@PathVariable("id") Integer id,HttpServletRequest request) {
        NocBusinessEntity business = nocBusinessService.getById(id);
        if(business!=null) {
            //获取展会模板，此行不能动
            NocTemplateEntity nocTemplateEntity = nocTemplateService.getById(business.getTid());
            request.setAttribute("template",nocTemplateEntity);
            request.setAttribute("id", id);
            request.setAttribute("ly", business.getLy());
            request.setAttribute("tid", business.getTid());
            request.setAttribute("business", business);
            return "modules/busi/ercode";
        }
        return "";
    }

    //啤酒节二维码 - 展商
    @RequestMapping(value = "/b/{id}")
    public String b(@PathVariable("id") Integer id,HttpServletRequest request) {
        NocBeerTicketBusinessEntity ticket = nocBeerTicketBusinessService.getById(id);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(ticket!=null) {
            //获取展会模板，此行不能动
            NocTemplateEntity nocTemplateEntity = nocTemplateService.getById(ticket.getTid());
            request.setAttribute("template",nocTemplateEntity);
            request.setAttribute("id", id);
            request.setAttribute("ly", "");
            request.setAttribute("tid", ticket.getTid());
            request.setAttribute("ticket", ticket);
            request.setAttribute("validDate",sdf.format(ticket.getValidDate()));
            request.setAttribute("location",businessSeat(sdf.format(ticket.getValidDate()),ticket.getBusinessId(),ticket.getId()));
            request.setAttribute("nowTime",sdf.format(new Date()));

            return "modules/beer/ercode_b";
        }
        return "";
    }

    public String businessSeat (String validDate,Integer businessId,Integer fid  ) {
        Map<String, Object> map = new HashMap<>();
        map.put("validDate", validDate);
        map.put("businessId", businessId);
        map.put("fid", fid);
        Map<String, Object> map1 = nocBeerSeatService.selectBusinessSeat(map);
        if (map1 != null) {
            String area = map1.get("area") + "";
            String tableRow = map1.get("table_row") + "";
            String tableNum = map1.get("table_num") + "";
            String seatNum = map1.get("seat_num") + "";
            String location = area + tableRow + tableNum + seatNum + "号";
            return location;
        }
        return "";
    }


    @RequestMapping("/b/bb")
    @ResponseBody
    public String businessCode (HttpServletRequest re ){
        String businessCode = nocBeerTicketBusinessService.getById(re.getParameter("id")).getErcode();
        return businessCode;
    }


    @RequestMapping("/b/sign")
    @ResponseBody
    public R getIsSign (HttpServletRequest re){
        Map<String,Object> map = new HashMap<>();
        map.put("id",re.getParameter("id"));
        String businessIsSign = nocBeerTicketBusinessService.getIsSign(map);
        return R.ok(businessIsSign);
    }






    /**
     * 获取短信验证码
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/h5/getCheckCode")
    @ResponseBody
    public R getCheckCode(String tid, String mobile) {
        Session session = this.getSession();
        // 发送短信，获取短信验证码
        String checkCode = this.sendCheckCode(tid,mobile);
        //String checkCode = "123456";
        if (StringUtils.isNotBlank(checkCode)) {
            // 将验证码放入缓存中
            session.setAttribute("checkCode",checkCode);
            Map<String,Object> map = new HashMap<>();
            map.put("checkCode",checkCode);
            map.put("msg","短信发送成功");
            return R.ok(map);
        } else {
            return R.error("短信发送失败");
        }
    }

    //腾讯
    @RequestMapping(value = "/orderApi", method = { RequestMethod.POST, RequestMethod.GET })
    @ResponseBody
    public JSONObject orderApi(String tid,String md,@RequestBody JSONObject param) {
        try {
            if (StringUtils.isNotEmpty(tid) ) {
                System.out.println(param.toJSONString());
                Map<String,Object> datas = (Map<String,Object>)param.get("data");
                List<Map<String,Object>> data = (List<Map<String,Object>>)datas.get("data");
                NocMemberEntity member = new NocMemberEntity();
                for(int i=0;i<data.size();i++){
                    Map<String,Object> obj = (Map<String,Object>)data.get(i);
                    String lable = (String)obj.get("label");
                    if("手机号".equals(lable)){
                        member.setCol1((String)obj.get("value"));
                    }
                    if("姓名".equals(lable)){
                        member.setCol3((String)obj.get("value"));
                    }
                    if("公司名".equals(lable)){
                        member.setCol2((String)obj.get("value"));
                    }
                    if("意向产品".equals(lable)){
                        member.setCol13((String)obj.get("value"));
                    }
                }
                if(StringUtils.isNotEmpty(member.getCol1())) {
                    Map<String, Object> p = new HashMap<>();
                    p.put("col1", member.getCol1());
                    p.put("tid", tid);
                    List<NocMemberEntity> list = (List<NocMemberEntity>) nocMemberService.listByMap(p);
                    if (list != null && list.size() > 0) {
                        //todo 用户已经存在
                    } else {
                        //生成二维码
                        String ercode = memberQRCodeUtil.getMemberQRCode(_pre);
                        if(StringUtils.isNotEmpty(ercode)){
                            member.setCol20(ercode);
                        }else{
                            member.setCol20(_pre+"000001");
                        }
                        //创建日期
                        member.setCreateTime(new Date());
                        //vip会员
                        member.setCol15("1");
                        member.setTid(Integer.parseInt(tid));
                        member.setLy("tengxun");
                        member.setCol10(md);
                        nocMemberService.save(member);
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject obj = new JSONObject();
        obj.put("code","0");
        obj.put("msg","success");
        return obj;
    }

}
